package sessionBean;

import entity.InsertItem;
import entity.Response;
import entity.ShortQResponse;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
@LocalBean
public class responseSessionBean {
    @PersistenceContext
    private EntityManager em;
    
    public Long createResponse(String userId, String question){ //create new response
        Response r = new Response();
        r.setUserId(userId);
        r.setQuestion(question);
        em.persist(r);
        em.flush();
        return r.getId();
    }
    
    public Long addShortQAnswer(Long responseId, Long questionId, String answer){ //add answers of interrupting questions to the response record
        InsertItem question = em.find(InsertItem.class, questionId);
        ShortQResponse shortQresponse = new ShortQResponse();
        shortQresponse.setQuestion(question); 
        shortQresponse.setAnswer(answer); 
        em.persist(shortQresponse); 
        Response r = em.find(Response.class, responseId);
        r.getShortQuestionAnswers().add(shortQresponse); 
        em.merge(r);
        em.flush();
        return r.getId();
    }
    
    public Long saveResponse(Long responseId, ArrayList<String> ideas){
        Response r = em.find(Response.class, responseId);
        r.setIdeas(ideas); 
        return null;
    }
    
    public Long deleteResponse(Long responseId){ //delete a particular record
        Response r = em.find(Response.class, responseId);
        for(ShortQResponse s : r.getShortQuestionAnswers()){
            s.setResponse(null); 
        }
        em.remove(r); 
        em.flush();
        return null;
    }
    
    public Response searchResponse(String userId){ //search a particular record
        String qryStr = "SELECT r FROM Response r WHERE r.userId = :User";
        Query query = em.createQuery(qryStr);
        query.setParameter("User", userId);
        Response r =  (Response)query.getSingleResult();
        return r;
    }
    
    public List getAllResponse(){ //get all response records
       String qryStr = "SELECT r FROM Response r";
        Query query = em.createQuery(qryStr);
        return query.getResultList();
    }
}
